<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="60%"
    v-dialog-drag
    :close-on-click-modal="false"
    top="6vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <PartitionTitle :title="title"></PartitionTitle>
    <el-form :model="form" ref="ruleForm" disabled label-width="110px">
      <el-form-item label="异常名称" prop="orderName">
        <el-input type="text" v-model="form.orderName"></el-input>
      </el-form-item>

      <el-form-item label="异常等级" prop="abnormalLevelName">
        <el-input type="text" v-model="form.abnormalLevelName"></el-input>
      </el-form-item>

      <el-form-item label="异常分类" prop="abnormalTypeName">
        <el-input type="text" v-model="form.abnormalTypeName"></el-input>
      </el-form-item>

      <el-form-item label="关联指标" prop='indexName' v-if='form.indexName'>
        <el-input type="text" v-model="form.indexName"></el-input>
      </el-form-item>

      <!-- <template v-if='form.indexName'> -->
        <el-form-item label="指标类型" prop='indexTypeName' v-if='form.indexName'>
          <el-input type="text" v-model="form.indexTypeName"></el-input>
        </el-form-item>

        <el-form-item label="所属工厂">
          <el-input type="text" v-model="form.factoryDeptName"></el-input>
        </el-form-item>

        <el-form-item label="所属车间">
          <el-input type="text" v-model="form.workshopName"></el-input>
        </el-form-item>

        <el-form-item label="所属产线">
          <el-input type="text" v-model="form.lineName"></el-input>
        </el-form-item>

        <el-form-item label="关联设备">
          <el-input type="text" v-model="form.equipmentName"></el-input>
        </el-form-item>
      <!-- </template> -->

      <template v-if='mode == "report"'>
        <el-form-item label="上报人">
          <el-input type="text" v-model="form.reportName"></el-input>
        </el-form-item>

        <el-form-item label="审核人">
          <el-input type="text" v-model="form.checkName "></el-input>
        </el-form-item>

        <el-form-item label="上报时间">
          <el-input type="text" v-model="form.reportDate"></el-input>
        </el-form-item>
      </template>

      <template v-if='mode == "distribute"'>
        <el-form-item label="下发人">
          <el-input type="text" v-model="form.reportName"></el-input>
        </el-form-item>

        <el-form-item label="责任人">
          <el-input type="text" v-model="form.processedName"></el-input>
        </el-form-item>

        <el-form-item label="下发时间">
          <el-input type="text" v-model="form.reportDate"></el-input>
        </el-form-item>
      </template>

      <el-form-item label="异常描述" prop='abnormalDes' style="width:100%">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2}"
          maxlength="150"
          show-word-limit
          placeholder="请输入异常描述"
          v-model="form.abnormalDes">
        </el-input>
      </el-form-item>

      <el-form-item label="附件" style="width:100%">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="{Authorization:token}"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload='beforeAvatarUpload'
          :on-success='handleSuccess'
          :accept="acceptFile"
          multiple
          :limit="10"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">请上传大小不超过 5MB 格式为 jpg/png/gif/pdf/doc/docx/xls/xlsx/ppt/pptx/jpeg/zip 的文件，最多10个。</div>
        </el-upload>
      </el-form-item>
    </el-form>

    <template v-if='mode == "report"'>
      <PartitionTitle title="审核信息"></PartitionTitle>
      <el-form :model="form" label-width="100px" disabled>
        <div style="width:100%">
          <el-form-item label="状态">
            <el-input type="text" v-model="approvalMap[form.status]"></el-input>
          </el-form-item>
        </div>

        <template v-if='form.status != 1'>
          <el-form-item label="审核人">
            <el-input type="text" v-model="form.checkName"></el-input>
          </el-form-item>

          <el-form-item label="审核时间">
            <el-input type="text" v-model="form.checkDate"></el-input>
          </el-form-item>

          <el-form-item label="反馈" style="width:100%">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2}"
              maxlength="150"
              show-word-limit
              placeholder="请输入异常描述"
              v-model="form.checkDes">
            </el-input>
          </el-form-item>
        </template>
      </el-form>
    </template>
  </el-dialog>
</template>
<script>
  import axios from 'axios'
  import { getToken } from '@/utils/auth'
  import service from "@//utils/request";
  import { GEN_SERVER } from '@/config/baseUrl'
  import { downloadFile } from '@/utils/file'
  import { parseTime } from '@/utils/eam'
  import { fileTypes } from '@/utils/file'
  import {getIndexConfigDetail} from "@/api/indexMgmt/configuration";
  import {approvalMap} from "../enum.js"
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },

    row: {
      type: Object,
      default: null
    },
    title:{
      type: String,
      default: null
    },
    // report:上报,distribute:下发
    mode:{
      type: String,
      default: null
    }
  },
  dicts: ["indexType"],
  data() {
    return {
      form: {},
      fileTypes,
      fileList:[],
      approvalMap,
      saveloading: false
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    },
    indexTypeDictMap() {
      return this.dictToMap(this.dict.indexType);
    },
    uploadUrl(){
      return service.baseURL + GEN_SERVER['form-server'] + '/refine/report/upload'
    },
    token() {
      return 'Bearer ' + getToken()
    },
    acceptFile(){
      return Object.values(this.fileTypes).join(",")
    }
  },

  created(){
  },

  methods: {
    handleClose() {
      this.resetFormData()
      this.saveloading = false;
    },
    handleOpen() {
      if (!this.row?.id) {
        this.resetFormData()
        return
      }
      this.form = Object.assign({},this.row)
      if(this.form?.indexCode){
        this.getIndexDetail()
      }
      if(this.form.files?.length){
        this.fileList = this.form.files.map(item => {
          return {
            name: item?.fileName,
            fileType:item.fileType,
            response: {
              data: item.id,
              code: 200
            }
          };
        });
      }
    },

    getIndexDetail(){
      getIndexConfigDetail(this.form?.indexCode)
      .then(res=>{
        if (res.code == 200 && res.data) {
          const indexItem = res.data;
          const {indexType} = indexItem?.indexMetaDto;
          const {
            indexConfigName,
            factoryDeptName,
            workshopName,
            lineName,
            equipName,
            id
          } = indexItem;
          this.form.indexCode = id;
          this.form.indexName = indexConfigName;
          this.form.indexType = indexType;
          this.$nextTick(()=>{
            this.$set(this.form,"indexTypeName",indexType ? this.indexTypeDictMap[indexType] : null)
          })
          this.form.factoryDeptName = factoryDeptName;
          this.form.workshopName = workshopName;
          this.form.lineName = lineName ? lineName : this.form.lineName;
          this.form.equipmentName = equipName ? equipName : this.form.equipmentName;
        }
      })
    },

    handleSuccess(response, file, fileList){
      this.fileList = fileList;
      this.form.fileIds = fileList.map(ele => ele.response?.data)
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      if(fileList?.length){
        this.form.fileIds = fileList.map(ele => ele.response?.data)
      }else{
        this.form.fileIds = []
      }
    },

    handlePreview(file) {
      axios({
        baseURL:service.baseURL + GEN_SERVER['form-server'],
        url:'/refine/report/byte/down',
        method:"get",
        params:{id:file.response.data},
        headers: {Authorization:'Bearer ' + getToken()},
        responseType: 'blob'
      }).then(res => {
        let count = file.name.lastIndexOf(".");
        let fileName = file.name.slice(0,count);
        let suffix = file.name.slice(count);
        downloadFile(res.data,`${fileName}${parseTime(new Date(), '{y}{m}{d}')}${suffix}`)
        this.saveloading = false
      }).catch(() => {
        this.msgError("操作失败")
        this.saveloading = false
      })
    },

    beforeAvatarUpload(file){
      if(!this.acceptFile.includes(file.type)){
        this.msgWarning("暂不支持上传该格式文件");
        return false
      }
      if(file.size / 1024 / 1024  > 5){
        this.msgWarning("上传的附件大小不得超过5M");
        return false
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10个文件，本次选择了 ${files.length} 个文件`);
      return false
    },

    resetFormData() {
      this.$refs.ruleForm?.resetFields();
      this.form = {};
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
  }
  .el-date-editor.el-input,
  .el-select {
    width: 100%;
  }
}
</style>
